package com.yao.springredisdemo.service.impl;

import com.yao.springredisdemo.dao.StudentRepository;
import com.yao.springredisdemo.entity.Student;
import com.yao.springredisdemo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * 使用springCache注解来操作
 *
 * @author yao
 */
@Service
@CacheConfig(cacheNames = "myCache")
public class StudentServiceTwoImpl implements StudentService {
    private StudentRepository studentRepository;

    @Autowired
    public StudentServiceTwoImpl(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    // @CachePut使用方法的返回值作为缓存的值
    @CachePut(key = "#student.getStudentId()")
    @Override
    public Student insertStudent(Student student) {
        return studentRepository.save(student);
    }

    @CacheEvict(key="#id")
    @Override
    public void deleteStudentById(Long id) {
        studentRepository.deleteById(id);
    }


    @Cacheable(key="#id")
    @Override
    public Student selectStudentById(Long id) {
        return studentRepository.getOne(id);
    }
}
